#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import render_template, request, Blueprint, jsonify
from my_app.record_policy.auto_record_policy import *
from my_app.cash_value.models import DataBaseConfig
from my_app.common.query_mysql_db import query_mysql_db
import traceback
from flask_login import login_required
import xlrd


record_policy = Blueprint("record_policy", __name__)


@login_required
@record_policy.route("/ajax-record-policy", methods=["POST", "GET"])
def policy_record():
    """保单录入页面渲染"""
    configs = [e for e in DataBaseConfig.query.all()]
    return render_template("record_policy/ajax-record-policy.html", configs=configs)


@record_policy.route("/query-spu-info", methods=["POST"])
def query_sup_info():
    """查询产品信息"""
    spu_id = request.form.get("sup_id")
    env_name = request.form.get("env_name")
    env_id = request.form.get("env_id")
    phone_num = request.form.get("phone_num")

    sku = return_all_sku_name(spu_id=spu_id, env=env_name)
    duty = return_all_duty_name(spu_id=spu_id, env=env_name)

    db_config = DataBaseConfig.query.get_or_404(env_id)
    db_dict = {
        "env": db_config.env, "host": db_config.host, "port": db_config.port,
        "username": db_config.username, "password": db_config.password,
        "database": db_config.database, "api_path": db_config.api_path
    }
    agency_data = query_mysql_db(
        db_config=db_dict, table="org_agency",
        condition=f"user_id IN (SELECT user_id FROM auth_user WHERE user_mobile = '{phone_num}')")
    if not agency_data:
        return jsonify({"status": 203, "data": "当前手机号查询无结果，请检查或更换手机号"})

    agency_id, org_id, company_id = agency_data[0], agency_data[1], agency_data[2]

    agreement_path = get_agreement_path(spu_id=spu_id, env=env_name, company_id=company_id)

    if sku and duty:
        sku = "\n".join(sku)
        duty = "\n".join(duty)
        return jsonify({
            "status": 200, "data": {
                "sku": sku, "duty": duty, "agreement": agreement_path,
                "agency_id": agency_id, "org_id": org_id, "company_id": company_id
            }
        })
    elif sku and not duty:
        sku = "\n".join(sku)
        duty = "此产品没有责任，请将责任名称置空，其余信息正常填写 然后在执行"
        return jsonify({
            "status": 200, "data": {
                "sku": sku, "duty": duty, "agreement": agreement_path,
                "agency_id": agency_id, "org_id": org_id, "company_id": company_id
            }
        })
    elif not sku and not duty:
        return jsonify({"status": 201, "data": "没有查询到任何的计划和责任，请确认环境以及产品ID正确"})
    else:
        return jsonify({"status": 202, "data": "未知的数据，请检查日志"})


@record_policy.route("/execute", methods=["POST"])
def execute():
    """执行"""
    env_name = request.form.get("env_name")
    file = request.files.get('file_input')
    company_id = request.form.get("company_id")
    agency_id = request.form.get("agency_id")
    accepted_time = request.form.get("accepted_time")
    if file:
        f = file.read()
        try:
            work_book = xlrd.open_workbook(file_contents=f)  # 接收二进制的文件内容
            sheet_name = work_book.sheet_by_index(0)
        except xlrd.biffh.XLRDError as e:
            return jsonify({"status": 201, "data": f"错误的源文件：{e} ；请确保文件的格式为xls！", "message": "添加失败"})
        except BaseException as e:
            return jsonify({"status": 202, "data": str(e), "message": "内部异常"})
        else:
            int_ls = []
            for row in range(1, sheet_name.nrows):
                # 将每个单元格的数据转换为字符串并加入列表
                row_values = [str(row_value) for row_value in sheet_name.row_values(row)]
                if row_values:
                    # 二次更新单元格数据 去除.0
                    _row_values = [row_v for row_v in row_values[:3]]
                    for j in row_values[3:]:
                        if ".0" in j:
                            _row_values.append(j[:-2])
                        else:
                            _row_values.append(j)
                    int_ls.append(_row_values)

            if int_ls:
                if company_id == '' or agency_id == '':
                    return jsonify({"status": 201, "data": "机构ID/代理人ID不可为空", "message": "缺少必要参数"})
                try:
                    data = run_main(env=env_name, data_list=int_ls, company_id=company_id,
                                    agency_id=agency_id, accepted_time=accepted_time)
                except BaseException as e:
                    print(traceback.print_exc())
                    return jsonify({"status": 500, "data": str(e), "message": "内部异常"})
                else:
                    return jsonify({"status": 200, "data": data, "message": "成功"})
            else:
                return jsonify({"status": 203, "data": "文件内容可能为空，请确认！", "message": "添加失败"})
    else:
        return jsonify({"status": 400, "data": "没有获取到文件对象！", "message": "添加失败"})






